<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/12
 * Time: 17:07
 */

namespace app\common\library;


class UploadService
{
    /*上传根目录*/
    const UPLOAD_ROOT_PATH = 'uploads/';

    /**
     * 设置文件名称
     * @return string
     */
    public static function setFileName()
    {
        return md5(uniqid(). time());
    }

    /**
     * 上传base64格式图片
     * @param $base64Data
     * @return bool|string
     * @throws \Exception
     */
    public static function uploadBase64Image($base64Data)
    {

        $base64Data = str_replace(' ', '+', $base64Data);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Data, $result)){
            //匹配成功
            $extension = $result[2];
            if (empty($extension) || !in_array($extension, ['jpg', 'gif', 'png', 'jpeg', 'bmp'])) {
                exception('上传图片格式有误');
            }
            $file_path = static::UPLOAD_ROOT_PATH .'avatars/'. date('Ymd').'/';
            $file_name = $file_path. md5(uniqid() . time()).'.'.$extension;
            if (is_dir($file_path) === false) {
                if (!mkdir($file_path, 0777, true)) {
                    exception('权限错误，生成文件夹失败');
                };
            }

            //服务器文件存储路径
            if (file_put_contents($file_name, base64_decode(str_replace($result[1], '', $base64Data)))) {
                return $file_name;
            } else {
                exception('上传图片失败');
            }
        } else {
            exception('不是base64图片文件');
        }
    }

}